package com.haust.community.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Auther: csp1999
 * @Date: 2020/11/26/21:12
 * @Description: 自定义日志处理组件
 */
@Component
@Aspect
public class ServiceLogAspect {

    // 获取日志工厂
    private static final Logger logger = LoggerFactory.getLogger(ServiceLogAspect.class);

    /**
     * 切入点
     */
    @Pointcut("execution(* com.haust.community.service.*.*(..))")
    public void pointcut() {

    }

    /**
     * 前置通知,在切面之前执行
     *
     * @param joinPoint
     */
    @Before("pointcut()")
    public void before(JoinPoint joinPoint) {
        // 用户[1.2.3.4],在[xxx],访问了[com.nowcoder.community.service.xxx()].
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            return;
        }
        HttpServletRequest request = attributes.getRequest();
        String ip = request.getRemoteHost();
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String target = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        logger.info(String.format("用户[%s],在[%s],访问了[%s].", ip, now, target));
    }

    /**
     * 后置通知,在切面之后执行
     */
    @After("pointcut()")
    public void doAfter() {
        logger.info("----------doAfter----------");
    }

    /**
     * 切入点拦截的方法执行结束后，捕获返回内容
     *
     * @param result
     */
    @AfterReturning(returning = "result", pointcut = "pointcut()")
    public void doAfterRuturn(Object result) {
        logger.info("捕获返回内容 : {}", result);
    }
}
